import { Component, OnInit} from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
import { config } from '../../shared/smartadmin.config';

declare var $: any;
declare var echarts: any;
declare var Viewer: any;
@Component({
	selector: 'sa-repaired-daily',
	templateUrl: './repaired-daily.component.html',
	styleUrls: ['./repaired-daily.component.css']
})
export class RepairedDailyComponent implements OnInit {
    tableData = []; //table数据
	totalCount: number = 0; //分页总条数
	curPage: number = 1; //分页当前页
	pageSize: number = 10; //内置的分页每页条数
	tableParam: any = {
//	    searchKey: '', //搜索keyword
        reportDate: '',
        companyName: '',//查询公司参数
        companyId: '',//查询公司参数
        userName: '',//录入人员
        export: '0',//是否导出  0:否  1:是
	}
	userList: any = [];//用户数据List
	constructor(private jsonApiService: JsonApiService, private router: Router, private activatedRoute: ActivatedRoute) {
		activatedRoute.queryParams.subscribe(queryParams => {
			this.curPage = queryParams.nowPage || 1;
		});
	}
	ngOnInit() {
	    this.initDate();
		this.initAllUser().then(() => {
			this.selectUserName();
		});
		this.load();
	}
	ngOnDestroy() {
		document.onclick = null;
	}
	// 初始化时间插件
    initDate(){
        let that=this;
        return new Promise(function(resolve,error){
            System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(() => {
                System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(() => {
                    $("#reportDate").datetimepicker({ //时间插件
                        format: "yyyy-mm-dd",
                        language: "zh-CN",
                        autoclose: true,
                        minView: 2,
                    })
                    resolve();
                })
            })
        });
    }
    // 时间擦除
    delReportDate(){
        $('#reportDate').val('');
        this.tableParam.reportDate = '';
    }
	//擦除用户所选值
	delUserName() {
		this.tableParam.userName = '';
		//采用简单粗暴的方法清除;官方推荐的方法失效
		var str = $("<span class='select2-selection__placeholder'>请选择</span>");
		$('#userNameSelect2').val("");
		$("#select2-userNameSelect2-container").empty();
		$("#select2-userNameSelect2-container").attr("title", "");
		$("#select2-userNameSelect2-container").prepend(str);
	}
	//初始化select2 选项
	selectUserName() {
		var that = this;
		System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
			System.import('assets/js/select2-zh-CN.js').then(() => {
				$("#userNameSelect2").select2({
					language: "zh-CN",
					placeholder: "请选择",
					allowClear: true,
					data: this.userList,//为Select添加数据
					templateResult: this.formatRepo
				}).on("select2:select", function (e) {
					var data = e.params.data;
					that.tableParam.userName = data.text;
				});
			})
		})
	}
	//select2 格式回调函数
	formatRepo(state) {
		if (!state.id) { return state.text };
		var $state = $('<span><i class="fa fa-user green"></i>&nbsp;&nbsp;' + state.text + '</span>');
		return $state;
	}
	//拉取
	initAllUser() {
		var that = this;
		return new Promise(function (resolve, reject) {
			that.jsonApiService.http("user/getUserList.html", null).subscribe(data => {
				if (data.success) {
					var userList = data.data;
					var selectdata = [];
					for (var i = 0; i < userList.length; i++) {
						var obj = {
							id: userList[i].userName,
							text: userList[i].name,
						}
						selectdata[i] = obj;
					}
				}
				that.userList = selectdata;
				resolve();
			})
		})
	}
	//table刷新
	refresh() {
		this.load();
	}
	//表格搜索
	table_search() {
		this.curPage = 1;
		this.tableParam.searchKey = common.stringTrim(this.tableParam.searchKey);
		this.load();
	}
    //分页回调
    paginate(e) {
        this.curPage = e.page + 1;
        this.pageSize = e.rows;
        this.load();
    }
	//初始化加载list数据
	load() {
	    this.tableParam.reportDate = $('#reportDate').val();
		let data = {
			pageSize: this.pageSize,
			nowPage: this.curPage,
			parameters: {
                reportDate: this.tableParam.reportDate,
                companyId: this.tableParam.companyId,//查询公司参数
                userName: this.tableParam.userName,//录入人员
                export: '0',//是否导出  0:否  1:是
            },
		}
		let reqdata = 'gridPager=' + JSON.stringify(data);
		this.jsonApiService.http("sanitation/sanitationReport/sanitationReportPage.html", reqdata).subscribe(result => {
			this.tableData = result.exhibitDatas || [];
			this.totalCount = result.recordCount;
		})
	}
	// 导出
	table_export(){
	    this.tableParam.reportDate = $('#reportDate').val();
	    let data = {
            pageSize: this.pageSize,
            nowPage: this.curPage,
            parameters: {
                reportDate: this.tableParam.reportDate,
                companyId: this.tableParam.companyId,//查询公司参数
                userName: this.tableParam.userName,//录入人员
                export: '1',//是否导出  0:否  1:是
            },
        }
		let timeCheck = common.correctTime(data.parameters, ['export'])
		if(!timeCheck.status){
			this.jsonApiService.message(timeCheck.message);
			return;
		}
	    common.exprotDataFile(data, "gridPager", config.BaseURL+'sanitation/sanitationReport/sanitationReportPage.html');
	}
	
	// 维修日报明细查看
	repairedDailyDetail(row){
	    this.router.navigate(['/installation-management/repaired-daily/repaired-daily-detail'],{ queryParams: { id: row.id}});
	}
	
	//公司选中回调
	companySelected(data) {
		this.tableParam.companyId = data.companyId;
		this.tableParam.companyName = data.companyName;
	}
	// 删除功能
	deleteRow(row){
		this.jsonApiService.confirm_message('删除维修记录会同步永久删除维修明细，确认要删除?').then(()=>{
			let reqdata = 'id=' + row.id;
			this.jsonApiService.http("sanitation/sanitationReport/deleteById.html", reqdata).subscribe(data => {
				this.jsonApiService.message(data.message);
				if(data.success){
					this.load();
				}
			})
		})
	}
}